package constants;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadFromParametersXML extends DefaultHandler {

	private SAXParserFactory spfac;
	private SAXParser sp;
	private String tmpValue;
	private String ip = null;
	private int port;
	private int maxPlayers;
	private int minPlayers;
	private int maxMoves;

	public ReadFromParametersXML(String fichero) throws ParserConfigurationException, SAXException, IOException {
		spfac = SAXParserFactory.newInstance();
		sp = spfac.newSAXParser();
		sp.parse(fichero, this);
	}

	public int getPort() {
		return port;
	}

	public String getIp() {
		return ip;
	}

	public int getMaxPlayers() {
		return maxPlayers;
	}

	public int getMinPlayers() {
		return minPlayers;
	}

	public int getMaxMoves() {
		return maxMoves;
	}

	public void startElement(String uri, String localName,String elementName, Attributes attributes) throws SAXException {

	}

	public void endElement(String s, String s1, String element) throws SAXException {

		if(element.equalsIgnoreCase("ip")) ip = tmpValue;

		else if(element.equalsIgnoreCase("port")) port = Integer.parseInt(tmpValue);
		
		else if(element.equalsIgnoreCase("maxplayers")) maxPlayers = Integer.parseInt(tmpValue);
		
		else if(element.equalsIgnoreCase("minplayers")) minPlayers = Integer.parseInt(tmpValue);
		
		else if(element.equalsIgnoreCase("maxmoves")) maxMoves = Integer.parseInt(tmpValue);

		else if(element.equalsIgnoreCase("PARAMETERS")){
			this.endDocument();
		}

	}

	public void characters(char[] ac, int i, int j) throws SAXException {
		tmpValue = new String(ac, i, j);
	}	
}//END PRIVATE CLASS
